package com.wjv.example.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>Title: PaymentService</p>
 * <p>Company:misspao </p>
 *
 * @author: wjv
 * @Date: Create in 17:03 2020/9/24
 * @Description:
 */
@Service
public class PaymentService {

    public String info1(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + "   paymentInfo_OK,id：  " + id + "\t" + "哈哈哈";
    }

    //失败
    @HystrixCommand(fallbackMethod = "timeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")  //3秒钟以内就是正常的业务逻辑
    })
    public String info2(Integer id) {
        int timeNumber = 3;
        try {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        int a = 10 / 0;
        return "线程池：" + Thread.currentThread().getName() + "   paymentInfo_TimeOut,id： " + id + " 请求成功 " + " 耗时(秒)" + timeNumber;
    }

    /**
     * 备用方法
     *
     * @param id
     * @param throwable 获取触发的异常
     * @return
     */
    private String timeoutHandler(Integer id, Throwable throwable) {
        throwable.printStackTrace();
        return "线程池：" + Thread.currentThread().getName() + "   系统繁忙, 请稍候再试, id：" + id;
    }

    /**
     * 测试服务熔断
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),  //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),   //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),  //时间范围
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), //失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(@RequestParam("id") Integer id){
        if (id < 0){
            throw new RuntimeException("*****id 不能负数");
        }
        String serialNumber = UUID.randomUUID().toString();

        return Thread.currentThread().getName()+" "+"调用成功,流水号："+serialNumber;
    }

    public String paymentCircuitBreakerFallback(Integer id, Throwable throwable){
        throwable.printStackTrace();
        return "id 不能负数，请稍候再试, id: " +id;
    }

}
